/*
 * 文件名               :  SocketHandler
 * 用途                    :  持有一个Socket,两个分别负责读写的线程
 * 最后修改日期:  $LastChangedDate: 2009-10-17 03:54:49 +0000 (Sat, 17 Oct 2009) $
 * 最后修改者     :  $LastChangedBy: wendal1985@gmail.com $
 * 创建者               :  Wendal Chen <wendal1985@gmail.com>
 */
package com.wendal.java.preproxy.thread;

import java.io.IOException;
import java.net.Socket;

import com.wendal.java.preproxy.bean.TerminateMessageBean;
import com.wendal.java.preproxy.bridge.BridgeConnector;
import com.wendal.java.preproxy.util.Toolkit;

public class SocketHandler extends Thread {

	private BridgeConnector connector;

	// private SocketHandlerFinder finder;

	private Socket socket;

	private ByteArrayInputThread byteArrayInputThread;

	private ByteArrayOutputThread byteArrayOutputThread;

	private String myID;

	public SocketHandler(BridgeConnector connector, Socket socket)
			throws IOException {
		this(connector, socket, Toolkit.creatdID(socket));
	}

	public SocketHandler(BridgeConnector connector, Socket socket, String myID)
			throws IOException {
		super();
		this.connector = connector;
		// this.finder = finder;
		this.socket = socket;

		this.myID = myID;
		byteArrayInputThread = new ByteArrayInputThread(socket, connector, myID);
		byteArrayOutputThread = new ByteArrayOutputThread(socket);
		// finder.addObject(myID, this);
	}

	@Override
	public void run() {
		byteArrayInputThread.start();
		byteArrayOutputThread.start();
		while (true) {
			if (byteArrayInputThread.isAlive()
					|| byteArrayOutputThread.isAlive()) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// Do nothing
				}
			} else {
				Toolkit.close(socket);
				// finder.remove(myID);
				if (!flag) {
					TerminateMessageBean messageBean = new TerminateMessageBean();
					messageBean.setFrom_id(myID);
					messageBean.setTerminateId(myID);
					connector.transfer(messageBean);
				}
				break;
			}
		}
	}

	public void writeData(byte[] data) {
		byteArrayOutputThread.addData(data);
	}

	private boolean flag;

	public void sendTerminateSign() {
		flag = true;
		if (byteArrayInputThread.isAlive())
			byteArrayInputThread.setFlag(true);
		if (byteArrayOutputThread.isAlive())
			byteArrayOutputThread.setFlag(true);
	}

	public String getMyID() {
		return myID;
	}
}
